#ifndef XGE_XTHREADDELEGATE_H_
#define XGE_XTHREADDELEGATE_H_
#include "xge_common_config.h"
#include "xsmart_ptr.h"

namespace xge{

  // Thread implementation
  // The user of the xge should NEVER be aware of there do exist the utility of thread!
  // Everything here is in the internal space , that is the reason .
  // They do things as the API documentation and what is more leave all the fucking messy
  // stuff to the xge coder .

namespace xge_internal{
  // XThread delegate
  // the running code and its data delegate
  // use the thread like this:
  // class XMyThreadDelegate: public ThreadDelegate {
  // ... 
  // };
  // ThreadManager::CreateXThread( ThreadDelegatePtr shared_ptr );

  class ThreadHandler;
  class ThreadManager;
  struct ThreadHandlerDeletor;
  struct ThreadDelegateDeletor;

  class ThreadDelegate : public Allocator {
  public: 
    // the thread main function 
    // you should rewrite this function in order to
    // do the work here
    virtual void ThreadMain() = 0;

    virtual ~ThreadDelegate()  {
      XASSERT_BINARY(EQ,INT,status(),THREAD_STATUS_RELEASE);
    }
    // every xthread-delegate has a status code
    // it is set by the thread function
    // when the thread do not need the xthread-delegate
    // it will anyway set the xthread-delegate to THREAD_STATUS_RELEASE
    enum {
      THREAD_STATUS_RUNNING = 0 ,
      THREAD_STATUS_RELEASE = 1 
    };

    int status() const {
      return status_;
    } 

    ThreadDelegate() : status_(THREAD_STATUS_RELEASE) {}

  private:
    // the status code 
    // it can only be changed by the ThreadManager and XThread 
    int status_;

    friend class ThreadHandler;
    friend class ThreadManager;
    friend class ThreadDelegate;
  };

  // ThreadDelegate deletor 
  struct ThreadDelegateDeletor {

    static void Destroy( ThreadDelegate* xthread_delegate ) {
      delete xthread_delegate;
    }

  };    
  // the ThreadDelegatePtr 
  // this ptr is the shared ptr , and as the handler accessors 
  typedef SharedPtr< ThreadDelegate , ThreadDelegateDeletor > ThreadDelegatePtr ;

} // namespace xge_internal

}// namespace xge
#endif// XGE_XTHREAD_H_